package com.kyzh.core.pager.weal.quanzi

import android.content.res.ColorStateList
import android.graphics.Color
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.chad.library.adapter.base.BaseMultiItemQuickAdapter
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.entity.MultiItemEntity
import com.chad.library.adapter.base.module.LoadMoreModule
import com.chad.library.adapter.base.viewholder.BaseDataBindingHolder
import com.gushenge.core.beans.DynamicBean
import com.gushenge.core.beans.DynamicGameBean
import com.gushenge.core.beans.QunBean
import com.gushenge.core.dao.GlobalKeys
import com.gushenge.core.requests.QuanZiRequest
import com.jeremyliao.liveeventbus.LiveEventBus
import com.kyzh.core.R
import com.kyzh.core.activities.BrowserActivity
import com.kyzh.core.pager.gamedetail.GameDetailActivity1
import com.kyzh.core.activities.PinglunActivity
import com.kyzh.core.adapters.Dynamic1Adapter
import com.kyzh.core.databinding.*
import com.gushenge.core.base.fragment.BaseFragment
import com.kyzh.core.utils.*
import com.littlejerk.rvdivider.builder.XGridBuilder
import com.shuyu.gsyvideoplayer.GSYVideoManager
import org.jetbrains.anko.backgroundResource
import org.jetbrains.anko.support.v4.onRefresh


class QuanZiDynamicFragment : BaseFragment() {
    companion object {
        fun newInstance(): QuanZiDynamicFragment {
            val args = Bundle()

            val fragment = QuanZiDynamicFragment()
            fragment.arguments = args
            return fragment
        }
    }

    private lateinit var binding: FragQuanziDynamicBinding
    private lateinit var topView: ItemRevBinding
    private var p: Int = 1
    private val adapter = QuanZiDynamicAdapter()
    private val topAdapter = TopAdapter()
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        binding = DataBindingUtil.inflate(inflater, R.layout.frag_quanzi_dynamic, container, false)
        topView = ItemRevBinding.inflate(layoutInflater)
        binding.lifecycleOwner = requireActivity()
        return binding.root
    }

    var ver: XGridBuilder? = null
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        ver =
            XGridBuilder(requireContext()).setSpacing(3f)//这几个Spacing的优先级可看XGridBuilder说明
                //这几个color和drawable的优先级可看XGridBuilder说明
                .setColor(Color.BLUE)
                //可设置颜色和drawable,drawable>color
                .setHLineColor(Color.WHITE)
                .setVLineColor(Color.WHITE)
                //是否包括边界
                .setIncludeEdge(false)
                //竖直和水平分割线交叉处绘制的是竖直分割线颜色（交叉处属于竖直分割线）
                .setVerticalIncludeEdge(true)

        binding.apply {
            rev.layoutManager = LinearLayoutManager(requireContext())
            rev.adapter = adapter
            swipe.onRefresh {
                p = 1
                swipe.isRefreshing = false

                getTop()
                getDynamic()
            }
            fab.setOnClickListener {
                PinglunActivity.start(requireActivity())
            }
        }
        getTop()
        getDynamic()
        adapter.loadMoreModule.setOnLoadMoreListener {
            p++
            getDynamic(p)
        }
        LiveEventBus.get<Boolean>("login").observe(requireActivity()) {
            if (it) {
                getDynamic()
                getTop()
            }
        }
    }

    private inner class TopAdapter :
        BaseQuickAdapter<QunBean, BaseDataBindingHolder<ItemQuanziTopBinding>>(
            R.layout.item_quanzi_top

        ) {
        override fun convert(
            holder: BaseDataBindingHolder<ItemQuanziTopBinding>,
            item: QunBean
        ) {
            holder.dataBinding?.data = item
            holder.itemView.setOnClickListener {
                if (checkLogin()) {
                    canJoin = true
                }
                if (startLogin()) {

                    startActivity<BrowserActivity>(
                        GlobalKeys.TITLE to item.name,
                        GlobalKeys.LINK to item.url
                    )

                }

            }
        }
    }

    private var canJoin: Boolean = false

    // 顶部显示加入群聊
    fun getTop() {
        QuanZiRequest.QuanZiQun {
            if (adapter.hasHeaderLayout()) {
                topAdapter.setNewInstance(this)
            } else {
                if (this.isNullOrEmpty()) {
                    adapter.removeAllHeaderView()
                } else {
                    topView.rev.apply {
                        backgroundResource = R.drawable.bg_dynamic_top
                        layoutManager =
                            LinearLayoutManager(requireContext(), RecyclerView.HORIZONTAL, false)
                        adapter = topAdapter
                    }
                    adapter.removeAllHeaderView()
                    adapter.addHeaderView(topView.root)
                    topAdapter.setNewInstance(this)
                }
            }
        }
    }

    var list: ArrayList<MultiItemEntity> = arrayListOf()

    fun getDynamic() {
        adapter.setNewInstance(null)
        QuanZiRequest.getDynamic(1) {


            this?.let {
                adapter.loadMoreModule.loadMoreComplete()
                if (p >= this.max_p) {
                    adapter.loadMoreModule.loadMoreEnd()
                    adapter.loadMoreModule.loadMoreEnd(true)
                }
                getDynamicGame(it.data)
            }
        }
    }

    fun getDynamic(p: Int = 1) {
        QuanZiRequest.getDynamic(p) {
            this?.let {
                adapter.loadMoreModule.loadMoreComplete()
                if (p >= this.max_p) {
                    adapter.loadMoreModule.loadMoreEnd()
                    adapter.loadMoreModule.loadMoreEnd(true)
                }
                if (p == 1) {
                    getDynamicGame(it.data)
                } else {
                    adapter.addData(it.data)
                }

            }
        }
    }

    fun getDynamicGame(DynamicBeans: ArrayList<DynamicBean>) {
        QuanZiRequest.getDynamicGame {
            var dex = 0
            DynamicBeans.forEachIndexed { index, dynamicBean ->
                adapter.addData(dynamicBean)
                if (index > 0 && (index + 1) % 3 == 0) {
                    if (this != null && dex < this.size - 1) {
                        this[dex].itemType = 1
                        adapter.addData(this[dex])
                        dex++
                    }
                }
            }

        }
    }


    private inner class QuanZiDynamicAdapter :
        BaseMultiItemQuickAdapter<MultiItemEntity, BaseDataBindingHolder<ViewDataBinding>>(list),
        LoadMoreModule {
        init {
            addItemType(0, R.layout.item_dynamic)
            addItemType(1, R.layout.item_dynamic_game)
        }

        override fun convert(
            holder: BaseDataBindingHolder<ViewDataBinding>,
            item: MultiItemEntity, convert: List<Any>
        ) {
            if (convert.isEmpty()) {
                onBindViewHolder(holder, holder.position)
            } else {
                when (item.itemType) {
                    0 -> {
                        val dynamicBean = item as DynamicBean
                        (holder.dataBinding as ItemDynamicBinding).apply {
                            tvZan.text = dynamicBean.zan.toString()

                            if (dynamicBean.is_zan == 0) {
                                //为点赞
                                val drawable = resources.getDrawable(R.drawable.ic_nozan)
                                tvZan.setCompoundDrawablesWithIntrinsicBounds(
                                    drawable,
                                    null,
                                    null,
                                    null
                                )

                            } else {
                                val drawable = resources.getDrawable(R.drawable.ic_zan1)
                                tvZan.setCompoundDrawablesWithIntrinsicBounds(
                                    drawable,
                                    null,
                                    null,
                                    null
                                )
                            }
                        }

                    }
                }

            }
        }

        override fun convert(
            holder: BaseDataBindingHolder<ViewDataBinding>,
            item: MultiItemEntity
        ) {
//            holder.setIsRecyclable(false)

            when (item.itemType) {
                0 -> {
                    val dynamicBean = item as DynamicBean
                    (holder.dataBinding as ItemDynamicBinding).data = dynamicBean
                    (holder.dataBinding as ItemDynamicBinding).apply {
                        root.setOnClickListener {
                            if (startLogin()) {
                                PingLunDetailActivity.start(requireContext(), item)
                            }
                        }
                        //点赞
                        tvZan.text = dynamicBean.zan.toString()
                        tvZan.setOnClickListener {
                            if (startLogin()) {
                                QuanZiRequest.DynamicZan(dynamicBean.id) {
                                    kotlin.runCatching {
                                        dynamicBean.is_zan =
                                            if (dynamicBean.is_zan == 0) {
                                                dynamicBean.zan += 1
                                                1
                                            } else {
                                                dynamicBean.zan -= 1
                                                0
                                            }
                                        notifyItemChanged(holder.position, R.id.tvZan)
                                    }
                                }
                            }
                        }
                        if (dynamicBean.is_zan == 0) {
                            //为点赞
                            val drawable = resources.getDrawable(R.drawable.ic_nozan)
                            tvZan.setCompoundDrawablesWithIntrinsicBounds(
                                drawable,
                                null,
                                null,
                                null
                            )
                        } else {
                            val drawable = resources.getDrawable(R.drawable.ic_zan1)
                            tvZan.setCompoundDrawablesWithIntrinsicBounds(
                                drawable,
                                null,
                                null,
                                null
                            )
                        }
                        //标签
                        if (dynamicBean.note.isNullOrEmpty()) {
                            tvTags.setVisibility(false)
                        } else {
                            tvTags.setVisibility(true)
                            if (dynamicBean.note == "常驻玩家") {
                                tvTags.setTextColor(Color.parseColor("#FFFF5D5D"))
                                tvTags.setBackgroundResource(R.drawable.bg_tips)
                                tvTags.backgroundTintList =
                                    (ColorStateList.valueOf(Color.parseColor("#FFFFECEC")))
                            } else if (dynamicBean.note == "资深玩家") {
                                tvTags.setTextColor(Color.parseColor("#FF6A3400"))
                                tvTags.setBackgroundResource(R.drawable.bg_tips)
                            } else {
                                tvTags.setVisibility(false)
                            }
                        }
                        // 名字模块
                        tvUserName.post {
                            tvUserName.setShader(dynamicBean.color)
                            tvUserName.setText(dynamicBean.pet_name)
                        }
                        if (!dynamicBean.video.isNullOrEmpty()) {
                            revImg.setVisibility(false)
                            videoPlayer.setVisibility(true)
                            if (dynamicBean.img != null && dynamicBean.img.size > 0) {
                                videoPlayer.setConfig(
                                    dynamicBean.video,
                                    dynamicBean.img[0],
                                    holder.position
                                )
                            } else {
                                videoPlayer.setConfig(dynamicBean.video, null, holder.position)
                            }

                        } else if (!dynamicBean.img.isNullOrEmpty()) {
                            // 展示图片
                            revImg.setVisibility(true)
                            videoPlayer.setVisibility(false)
                            val gridLayoutManager = GridLayoutManager(requireContext(), 6)
                            val value = object : GridLayoutManager.SpanSizeLookup() {
                                override fun getSpanSize(position: Int): Int {
                                    return when (dynamicBean.img.size) {
                                        1 -> 6
                                        2 -> 3
                                        else -> 2
                                    }
                                }
                            }
                            gridLayoutManager.spanSizeLookup = value
                            if (revImg.itemDecorationCount > 0) {
                                val itemDecorationAt = revImg.getItemDecorationAt(0)
                                if (itemDecorationAt == null) {
                                    revImg.addItemDecoration(ver!!.build())
                                }
                            } else {
                                revImg.addItemDecoration(ver!!.build())
                            }
                            revImg.layoutManager = gridLayoutManager

                            val gameDetailBannerAdapter = Dynamic1Adapter(
                                R.layout.game_detail_banner_item1,
                                dynamicBean.img,
                                item.video
                            )
                            revImg.adapter = gameDetailBannerAdapter
                            gameDetailBannerAdapter.setOnItemClickListener { adapter, view, position ->
                                reviewImages(dynamicBean.img, position)
                            }
                        } else {
                            // 不展示
                            videoPlayer.setVisibility(false)
                            revImg.setVisibility(false)
                        }
                    }
                }
                1 -> {
                    val dynamicBean = item as DynamicGameBean
                    (holder.dataBinding as ItemDynamicGameBinding).apply {
                        root.setOnClickListener {
                            GameDetailActivity1.start(requireContext(), item.id)
                        }
                        data = dynamicBean

                        runCatching {
                            if (dynamicBean.point.isNotEmpty()) {
                                rb.rating = dynamicBean.point.toFloat()

                            }
                        }
                        tvType.text = "${item.point}  ${item.type}   ${item.size}"
                        tvDown.setOnClickListener {
                            GameDetailActivity1.start(requireContext(), item.id)
                        }
                    }

                }
            }
        }


    }


    override fun onPause() {
        GSYVideoManager.onPause()
        super.onPause()
    }
}